﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using HslCommunication.BasicFramework;

namespace HslCommunication.Core
{
	/// <summary>
	/// HslCommunication的一些静态辅助方法<br />
	/// Some static auxiliary methods of HslCommunication
	/// </summary>
	// Token: 0x02000129 RID: 297
	public class HslHelper
	{
		/// <summary>
		/// 解析地址的附加参数方法，比如你的地址是s=100;D100，可以提取出"s"的值的同时，修改地址本身，如果"s"不存在的话，返回给定的默认值<br />
		/// The method of parsing additional parameters of the address, for example, if your address is s=100;D100, you can extract the value of "s" and modify the address itself. If "s" does not exist, return the given default value
		/// </summary>
		/// <param name="address">复杂的地址格式，比如：s=100;D100</param>
		/// <param name="paraName">等待提取的参数名称</param>
		/// <param name="defaultValue">如果提取的参数信息不存在，返回的默认值信息</param>
		/// <returns>解析后的新的数据值或是默认的给定的数据值</returns>
		// Token: 0x06001953 RID: 6483 RVA: 0x0007F8F0 File Offset: 0x0007DAF0
		public static int ExtractParameter(ref string address, string paraName, int defaultValue)
		{
			OperateResult<int> operateResult = HslHelper.ExtractParameter(ref address, paraName);
			return operateResult.IsSuccess ? operateResult.Content : defaultValue;
		}

		/// <summary>
		/// 解析地址的附加参数方法，比如你的地址是s=100;D100，可以提取出"s"的值的同时，修改地址本身，如果"s"不存在的话，返回错误的消息内容<br />
		/// The method of parsing additional parameters of the address, for example, if your address is s=100;D100, you can extract the value of "s" and modify the address itself. 
		/// If "s" does not exist, return the wrong message content
		/// </summary>
		/// <param name="address">复杂的地址格式，比如：s=100;D100</param>
		/// <param name="paraName">等待提取的参数名称</param>
		/// <returns>解析后的参数结果内容</returns>
		// Token: 0x06001954 RID: 6484 RVA: 0x0007F91C File Offset: 0x0007DB1C
		public static OperateResult<int> ExtractParameter(ref string address, string paraName)
		{
			OperateResult<int> result;
			try
			{
				Match match = Regex.Match(address, paraName + "=[0-9A-Fa-fx]+;");
				bool flag = !match.Success;
				if (flag)
				{
					result = new OperateResult<int>(string.Concat(new string[]
					{
						"Address [",
						address,
						"] can't find [",
						paraName,
						"] Parameters. for example : ",
						paraName,
						"=1;100"
					}));
				}
				else
				{
					string text = match.Value.Substring(paraName.Length + 1, match.Value.Length - paraName.Length - 2);
					int value = text.StartsWith("0x") ? Convert.ToInt32(text.Substring(2), 16) : (text.StartsWith("0") ? Convert.ToInt32(text, 8) : Convert.ToInt32(text));
					address = address.Replace(match.Value, "");
					result = OperateResult.CreateSuccessResult<int>(value);
				}
			}
			catch (Exception ex)
			{
				result = new OperateResult<int>(string.Concat(new string[]
				{
					"Address [",
					address,
					"] Get [",
					paraName,
					"] Parameters failed: ",
					ex.Message
				}));
			}
			return result;
		}

		/// <summary>
		/// 解析地址的起始地址的方法，比如你的地址是 A[1] , 那么将会返回 1，地址修改为 A，如果不存在起始地址，那么就不修改地址，返回 -1<br />
		/// The method of parsing the starting address of the address, for example, if your address is A[1], then it will return 1, 
		/// and the address will be changed to A. If the starting address does not exist, then the address will not be changed and return -1
		/// </summary>
		/// <param name="address">复杂的地址格式，比如：A[0] </param>
		/// <returns>如果存在，就起始位置，不存在就返回 -1</returns>
		// Token: 0x06001955 RID: 6485 RVA: 0x0007FA64 File Offset: 0x0007DC64
		public static int ExtractStartIndex(ref string address)
		{
			int result;
			try
			{
				Match match = Regex.Match(address, "\\[[0-9]+\\]$");
				bool flag = !match.Success;
				if (flag)
				{
					result = -1;
				}
				else
				{
					string value = match.Value.Substring(1, match.Value.Length - 2);
					int num = Convert.ToInt32(value);
					address = address.Remove(address.Length - match.Value.Length);
					result = num;
				}
			}
			catch
			{
				result = -1;
			}
			return result;
		}

		/// <summary>
		/// 解析地址的附加参数方法，比如你的地址是s=100;D100，可以提取出"s"的值的同时，修改地址本身，如果"s"不存在的话，返回错误的消息内容<br />
		/// The method of parsing additional parameters of the address, for example, if your address is s=100;D100, you can extract the value of "s" and modify the address itself. 
		/// If "s" does not exist, return the wrong message content
		/// </summary>
		/// <param name="address">复杂的地址格式，比如：s=100;D100</param>
		/// <param name="defaultTransform">默认的数据转换信息</param>
		/// <returns>解析后的参数结果内容</returns>
		// Token: 0x06001956 RID: 6486 RVA: 0x0007FAF0 File Offset: 0x0007DCF0
		public static IByteTransform ExtractTransformParameter(ref string address, IByteTransform defaultTransform)
		{
			bool flag = !Authorization.asdniasnfaksndiqwhawfskhfaiw();
			IByteTransform result;
			if (flag)
			{
				result = defaultTransform;
			}
			else
			{
				try
				{
					string text = "format";
					Match match = Regex.Match(address, text + "=(ABCD|BADC|DCBA|CDAB);", RegexOptions.IgnoreCase);
					bool flag2 = !match.Success;
					if (flag2)
					{
						result = defaultTransform;
					}
					else
					{
						string text2 = match.Value.Substring(text.Length + 1, match.Value.Length - text.Length - 2);
						DataFormat dataFormat = defaultTransform.DataFormat;
						string text3 = text2.ToUpper();
						string a = text3;
						if (!(a == "ABCD"))
						{
							if (!(a == "BADC"))
							{
								if (!(a == "DCBA"))
								{
									if (a == "CDAB")
									{
										dataFormat = DataFormat.CDAB;
									}
								}
								else
								{
									dataFormat = DataFormat.DCBA;
								}
							}
							else
							{
								dataFormat = DataFormat.BADC;
							}
						}
						else
						{
							dataFormat = DataFormat.ABCD;
						}
						address = address.Replace(match.Value, "");
						bool flag3 = dataFormat != defaultTransform.DataFormat;
						if (flag3)
						{
							result = defaultTransform.CreateByDateFormat(dataFormat);
						}
						else
						{
							result = defaultTransform;
						}
					}
				}
				catch
				{
					throw;
				}
			}
			return result;
		}

		/// <summary>
		/// 切割当前的地址数据信息，根据读取的长度来分割成多次不同的读取内容，需要指定地址，总的读取长度，切割读取长度<br />
		/// Cut the current address data information, and divide it into multiple different read contents according to the read length. 
		/// You need to specify the address, the total read length, and the cut read length
		/// </summary>
		/// <param name="address">整数的地址信息</param>
		/// <param name="length">读取长度信息</param>
		/// <param name="segment">切割长度信息</param>
		/// <returns>切割结果</returns>
		// Token: 0x06001957 RID: 6487 RVA: 0x0007FC1C File Offset: 0x0007DE1C
		public static OperateResult<int[], int[]> SplitReadLength(int address, ushort length, ushort segment)
		{
			int[] array = SoftBasic.SplitIntegerToArray((int)length, (int)segment);
			int[] array2 = new int[array.Length];
			for (int i = 0; i < array2.Length; i++)
			{
				bool flag = i == 0;
				if (flag)
				{
					array2[i] = address;
				}
				else
				{
					array2[i] = array2[i - 1] + array[i - 1];
				}
			}
			return OperateResult.CreateSuccessResult<int[], int[]>(array2, array);
		}

		/// <summary>
		/// 根据指定的长度切割数据数组，返回地址偏移量信息和数据分割信息
		/// </summary>
		/// <typeparam name="T">数组类型</typeparam>
		/// <param name="address">起始的地址</param>
		/// <param name="value">实际的数据信息</param>
		/// <param name="segment">分割的基本长度</param>
		/// <param name="addressLength">一个地址代表的数据长度</param>
		/// <returns>切割结果内容</returns>
		// Token: 0x06001958 RID: 6488 RVA: 0x0007FC7C File Offset: 0x0007DE7C
		public static OperateResult<int[], List<T[]>> SplitWriteData<T>(int address, T[] value, ushort segment, int addressLength)
		{
			List<T[]> list = SoftBasic.ArraySplitByLength<T>(value, (int)segment * addressLength);
			int[] array = new int[list.Count];
			for (int i = 0; i < array.Length; i++)
			{
				bool flag = i == 0;
				if (flag)
				{
					array[i] = address;
				}
				else
				{
					array[i] = array[i - 1] + list[i - 1].Length / addressLength;
				}
			}
			return OperateResult.CreateSuccessResult<int[], List<T[]>>(array, list);
		}

		/// <summary>
		/// 获取地址信息的位索引，在地址最后一个小数点的位置
		/// </summary>
		/// <param name="address">地址信息</param>
		/// <returns>位索引的位置</returns>
		// Token: 0x06001959 RID: 6489 RVA: 0x0007FCE8 File Offset: 0x0007DEE8
		public static int GetBitIndexInformation(ref string address)
		{
			int result = 0;
			int num = address.LastIndexOf('.');
			bool flag = num > 0 && num < address.Length - 1;
			if (flag)
			{
				string text = address.Substring(num + 1);
				bool flag2 = text.Contains("A") || text.Contains("B") || text.Contains("C") || text.Contains("D") || text.Contains("E") || text.Contains("F");
				if (flag2)
				{
					result = Convert.ToInt32(text, 16);
				}
				else
				{
					result = Convert.ToInt32(text);
				}
				address = address.Substring(0, num);
			}
			return result;
		}

		/// <summary>
		/// 从当前的字符串信息获取IP地址数据，如果是ip地址直接返回，如果是域名，会自动解析IP地址，否则抛出异常<br />
		/// Get the IP address data from the current string information, if it is an ip address, return directly, 
		/// if it is a domain name, it will automatically resolve the IP address, otherwise an exception will be thrown
		/// </summary>
		/// <param name="value">输入的字符串信息</param>
		/// <returns>真实的IP地址信息</returns>
		// Token: 0x0600195A RID: 6490 RVA: 0x0007FDA8 File Offset: 0x0007DFA8
		public static string GetIpAddressFromInput(string value)
		{
			bool flag = !string.IsNullOrEmpty(value);
			if (flag)
			{
				bool flag2 = Regex.IsMatch(value, "^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$");
				if (flag2)
				{
					IPAddress ipaddress;
					bool flag3 = !IPAddress.TryParse(value, out ipaddress);
					if (flag3)
					{
						throw new Exception(StringResources.Language.IpAddressError);
					}
					return value;
				}
				else
				{
					IPHostEntry hostEntry = Dns.GetHostEntry(value);
					IPAddress[] addressList = hostEntry.AddressList;
					bool flag4 = addressList.Length != 0;
					if (flag4)
					{
						return addressList[0].ToString();
					}
				}
			}
			return "127.0.0.1";
		}

		/// <summary>
		/// 从流中接收指定长度的字节数组
		/// </summary>
		/// <param name="stream">流</param>
		/// <param name="length">数据长度</param>
		/// <returns>二进制的字节数组</returns>
		// Token: 0x0600195B RID: 6491 RVA: 0x0007FE34 File Offset: 0x0007E034
		public static byte[] ReadSpecifiedLengthFromStream(Stream stream, int length)
		{
			byte[] array = new byte[length];
			int i = 0;
			while (i < length)
			{
				int num = stream.Read(array, i, array.Length - i);
				i += num;
				bool flag = num == 0;
				if (flag)
				{
					break;
				}
			}
			return array;
		}

		/// <summary>
		/// 将字符串的内容写入到流中去
		/// </summary>
		/// <param name="stream">数据流</param>
		/// <param name="value">字符串内容</param>
		// Token: 0x0600195C RID: 6492 RVA: 0x0007FE7C File Offset: 0x0007E07C
		public static void WriteStringToStream(Stream stream, string value)
		{
			byte[] value2 = string.IsNullOrEmpty(value) ? new byte[0] : Encoding.UTF8.GetBytes(value);
			HslHelper.WriteBinaryToStream(stream, value2);
		}

		/// <summary>
		/// 从流中读取一个字符串内容
		/// </summary>
		/// <param name="stream">数据流</param>
		/// <returns>字符串信息</returns>
		// Token: 0x0600195D RID: 6493 RVA: 0x0007FEB0 File Offset: 0x0007E0B0
		public static string ReadStringFromStream(Stream stream)
		{
			byte[] bytes = HslHelper.ReadBinaryFromStream(stream);
			return Encoding.UTF8.GetString(bytes);
		}

		/// <summary>
		/// 将二进制的内容写入到数据流之中
		/// </summary>
		/// <param name="stream">数据流</param>
		/// <param name="value">原始字节数组</param>
		// Token: 0x0600195E RID: 6494 RVA: 0x0007FED4 File Offset: 0x0007E0D4
		public static void WriteBinaryToStream(Stream stream, byte[] value)
		{
			stream.Write(BitConverter.GetBytes(value.Length), 0, 4);
			stream.Write(value, 0, value.Length);
		}

		/// <summary>
		/// 从流中读取二进制的内容
		/// </summary>
		/// <param name="stream">数据流</param>
		/// <returns>字节数组</returns>
		// Token: 0x0600195F RID: 6495 RVA: 0x0007FEF4 File Offset: 0x0007E0F4
		public static byte[] ReadBinaryFromStream(Stream stream)
		{
			byte[] value = HslHelper.ReadSpecifiedLengthFromStream(stream, 4);
			int num = BitConverter.ToInt32(value, 0);
			bool flag = num <= 0;
			byte[] result;
			if (flag)
			{
				result = new byte[0];
			}
			else
			{
				result = HslHelper.ReadSpecifiedLengthFromStream(stream, num);
			}
			return result;
		}

		/// <summary>
		/// 从字符串的内容提取UTF8编码的字节，加了对空的校验
		/// </summary>
		/// <param name="message">字符串内容</param>
		/// <returns>结果</returns>
		// Token: 0x06001960 RID: 6496 RVA: 0x0007FF34 File Offset: 0x0007E134
		public static byte[] GetUTF8Bytes(string message)
		{
			return string.IsNullOrEmpty(message) ? new byte[0] : Encoding.UTF8.GetBytes(message);
		}

		/// <summary>
		/// 将多个路径合成一个更完整的路径，这个方法是多平台适用的
		/// </summary>
		/// <param name="paths">路径的集合</param>
		/// <returns>总路径信息</returns>
		// Token: 0x06001961 RID: 6497 RVA: 0x0007FF64 File Offset: 0x0007E164
		public static string PathCombine(params string[] paths)
		{
			return Path.Combine(paths);
		}

		/// <summary>
		/// <b>[商业授权]</b> 将原始的字节数组，转换成实际的结构体对象，需要事先定义好结构体内容，否则会转换失败<br />
		/// <b>[Authorization]</b> To convert the original byte array into an actual structure object, 
		/// the structure content needs to be defined in advance, otherwise the conversion will fail
		/// </summary>
		/// <typeparam name="T">自定义的结构体</typeparam>
		/// <param name="content">原始的字节内容</param>
		/// <returns>是否成功的结果对象</returns>
		// Token: 0x06001962 RID: 6498 RVA: 0x0007FF7C File Offset: 0x0007E17C
		public static OperateResult<T> ByteArrayToStruct<T>(byte[] content) where T : struct
		{
			bool flag = !Authorization.asdniasnfaksndiqwhawfskhfaiw();
			OperateResult<T> result;
			if (flag)
			{
				result = new OperateResult<T>(StringResources.Language.InsufficientPrivileges);
			}
			else
			{
				int num = Marshal.SizeOf(typeof(T));
				IntPtr intPtr = Marshal.AllocHGlobal(num);
				try
				{
					Marshal.Copy(content, 0, intPtr, num);
					T value = Marshal.PtrToStructure<T>(intPtr);
					Marshal.FreeHGlobal(intPtr);
					result = OperateResult.CreateSuccessResult<T>(value);
				}
				catch (Exception ex)
				{
					Marshal.FreeHGlobal(intPtr);
					result = new OperateResult<T>(ex.Message);
				}
			}
			return result;
		}

		/// <summary>
		/// 根据当前的位偏移地址及读取位长度信息，计算出实际的字节索引，字节数，字节位偏移
		/// </summary>
		/// <param name="addressStart">起始地址</param>
		/// <param name="length">读取的长度</param>
		/// <param name="newStart">返回的新的字节的索引，仍然按照位单位</param>
		/// <param name="byteLength">字节长度</param>
		/// <param name="offset">当前偏移的信息</param>
		// Token: 0x06001963 RID: 6499 RVA: 0x00080010 File Offset: 0x0007E210
		public static void CalculateStartBitIndexAndLength(int addressStart, ushort length, out int newStart, out ushort byteLength, out int offset)
		{
			byteLength = (ushort)((addressStart + (int)length - 1) / 8 - addressStart / 8 + 1);
			offset = addressStart % 8;
			newStart = addressStart - offset;
		}
	}
}
